package com.xiyang.security.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * @author xiyang.ycj
 * @since Jun 25, 2019 02:11:49 AM
 */
@Entity
@Table(name = "role",catalog = "xiyang_operater")
public class Role implements Serializable {

    private static final long serialVersionUID = -3417223392804225864L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer roleId;
    private String  rolename;

   /* @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id",nullable = false) // 外键列是否可以为空。
    private User user; // 角色对应的用户实体*/

    // mappedBy="role"
    // 说明在两个关联的实体Bean中,permission这一端是关系的拥有者,permission一方的表中生成到关联类的外键
    // 且mappedBy只有在双向关联时,才会使用这个属性
 /*   @OneToMany(fetch = FetchType.EAGER,mappedBy = "role") // user 是对应的实体类中 字段名，避免产生中间表
    private Set<Permission> permissions = new HashSet<>(0); // 对应的角色集合*/

    @ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.PERSIST)
    @JoinTable(name = "role_permission", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = {
            @JoinColumn(name = "permission_id") })//joinColumns写的都是本表在中间表的外键名称， inverseJoinColumns写的是另一个表在中间表的外键名称。
    @JsonIgnore
    private Set<Permission> permissions;

    @Transient
    @JsonIgnore
    private Set<String> url;


    public Role() {
    }

    public Role(Integer roleId ,String rolename, Set<Permission> permissions, Set<String> url) {
        this.roleId = roleId;
        this.rolename = rolename;
        this.permissions = permissions;
        this.url = url;
    }

    public Integer getRoleId() {
        return roleId;
    }

    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }

    public String getRolename() {
        return rolename;
    }

    public void setRolename(String rolename) {
        this.rolename = rolename;
    }


    public Set<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(Set<Permission> permissions) {
        this.permissions = permissions;
    }



    public Set<String> getUrl() {
        if(url==null){
            url=new HashSet<>();
            for (Permission permission : permissions) {
                this.url.add(permission.getUrl());
            }
        }
        return url;
    }

    public void setUrl(Set<String> url) {
        this.url = url;
    }

    @Override
    public String toString() {
        return "Role{" +
                "roleId=" + roleId +
                ", rolename='" + rolename + '\'' +
                ", url=" + url +
                '}';
    }
}
